<?php
use Illuminate\Support\Facades\DB;

/**
 * 获取指定表的某个字段的值
 * @param $id 值
 * @param $tbName 表名
 * @param $tbid 值对应的字段名
 * @param $field 获取该字段的值
 */
function getValue($id, $tbName ,$tbid, $field ){
    $str = db::table("$tbName")->where($tbid , $id)->value($field);
    if(is_array($str)){
        foreach ($str as $k=>$v){
            $str = implode("", $v);
        }
    }
    return $str;
}

function format_bytes($size) {
    $units = array(' B', ' KB', ' MB', ' GB', ' TB');
    for ($i = 0; $size >= 1024 && $i < 4; $i++) $size /= 1024;
    return round($size, 2).$units[$i];
}

function getFieldValue($unit_id, $type_id ,$field_id ){
    $map['unit_id'] = $unit_id;
    $map['type_id'] = $type_id;
    $map['field_id'] = $field_id;
    $str = db::table("unit_type_field_value")->where($map)->value('val');
    return $str;
}

function format_time($seconds) {
    $seconds = (int) $seconds;
    if ($seconds < 86400) {//如果不到一天
        $total_time = gmstrftime('%H时%M分%S秒', $seconds);
    } else {
        $total_time = explode(' ', gmstrftime('%j %H %M %S', $seconds));
        $total_time = ($total_time[0] - 1) . '天' . $total_time[1] . '时' . $total_time[2] . '分' . $total_time[3]. '秒';
    }
    return $total_time;
}

function get_client_ip() {
    $ip=false;
    if(!empty($_SERVER["HTTP_CLIENT_IP"])){
        $ip = $_SERVER["HTTP_CLIENT_IP"];
    }
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
        if ($ip) { array_unshift($ips, $ip); $ip = FALSE; }
        for ($i = 0; $i < count($ips); $i++) {
            if (!eregi ("^(10│172.16│192.168).", $ips[$i])) {
                $ip = $ips[$i];
                break;
            }
        }
    }
    return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}

function getLastSql() {
    DB::listen(function ($sql) {
        foreach ($sql->bindings as $i => $binding) {
            if ($binding instanceof \DateTime) {
                $sql->bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
            } else {
                if (is_string($binding)) {
                    $sql->bindings[$i] = "'$binding'";
                }
            }
        }
        $query = str_replace(array('%', '?'), array('%%', '%s'), $sql->sql);
        $query = vsprintf($query, $sql->bindings);
        print_r($query);
        echo '<br />';
    });
}





